package com.hnucm.onlinealgstudy.controller;

import com.hnucm.onlinealgstudy.pojo.Approval;
import com.hnucm.onlinealgstudy.pojo.User;
import com.hnucm.onlinealgstudy.pojo.UserInfo;
import com.hnucm.onlinealgstudy.service.UserService;
import com.hnucm.onlinealgstudy.utils.ResultOBJ;
import com.hnucm.onlinealgstudy.utils.SYSConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/oasadapi/users")
public class UserController {
    @Autowired
    UserService userService;
    // 获取用户列表信息接口
    @GetMapping
    public List<User> getUserList(User user) {
        return userService.getUserList(user);
    }
    // 获取指定条件的用户列表
    @GetMapping(value = "/search")
    public List<User> getAllUserList(String user_name, String start_time, String end_time){
        System.out.println(user_name);
        System.out.println(start_time);
        int flag=0;
        if(start_time.isEmpty()){flag=1;}
        Date date1=new Date();
        Date date2=new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
             date1 = sdf.parse(start_time);
             date2 = sdf.parse(end_time);
//            System.out.println(date1);
//            System.out.println(date2);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Timestamp t1=new Timestamp(date1.getTime());
        Timestamp t2=new Timestamp(date2.getTime());
//        System.out.println(t1);
//        System.out.println(t2);
        if(flag==1){t1=null;t2=null;}
        List<User> userList = userService.getAllUserList(user_name, t1, t2);
//        System.out.println(userList);
        return userList;
    }
    // 根据用户id查找用户信息接口
    // c+a+t try快捷键
    @PostMapping("/{id}")
    public ResultOBJ getUserById(@PathVariable Integer id) {
        try {
            List<User> list=userService.findUserById(id);
            if(list.isEmpty()){
                throw new RuntimeException();
            }
            return new ResultOBJ(SYSConstant.Code_Success,SYSConstant.Find_Success,list.get(0));
        } catch (Exception e) {
            return new ResultOBJ(SYSConstant.Code_Error,SYSConstant.Find_Error);
        }
    }

    // 用户登录接口
    @PostMapping("/login")
    public ResultOBJ login(@RequestBody User user) {
        try {
            List<User> list=userService.getUserList(user);
            if(list.isEmpty()){
                throw new RuntimeException();
            }
            return new ResultOBJ(SYSConstant.Code_Success,SYSConstant.Login_Success,list.get(0));
        } catch (Exception e) {
            return new ResultOBJ(SYSConstant.Code_Error,SYSConstant.Login_Error);
        }
    }

    // 上传头像功能
    @PostMapping("/upload")
    public ResultOBJ upload(@RequestParam(value = "file",required = false) MultipartFile file){
        if(file.isEmpty()) return ResultOBJ.UPLOAD_WARNING;
        // 获取前端传过来的文件名
        String originalFilename=file.getOriginalFilename();
        // 给文件命名
        // String filename=originalFilename.substring(0,originalFilename.lastIndexOf("."))+System.currentTimeMillis()+"."+originalFilename.substring(originalFilename.lastIndexOf(".")+1);
        // 保存地址
        String path="E:\\workspace\\OASAD\\src\\assets\\avatar\\";
        // 判断文件是否存在
        File dest = new File(path+originalFilename);
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        // 上传
        try {
            file.transferTo(dest);
            return ResultOBJ.UPLOAD_SUCCESS;
        } catch (IOException e) {
            return ResultOBJ.UPLOAD_SUCCESS;
        }
    }

    // 注册用户接口
    @PostMapping
    public ResultOBJ addUser(@RequestBody User user){
        try {
            String user_name=user.getUser_name();
            List<User> list=userService.findUserByName(user_name);
            if(list.isEmpty()){
                String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
                user.setJoin_time(date);
                userService.addUser(user);
                List<User> users=userService.findUserByName(user_name);
                return new ResultOBJ(SYSConstant.Code_Success,SYSConstant.Enroll_Success,users.get(0));
            }
            else {
                return ResultOBJ.ENROLL_ERROR;
            }
        } catch (Exception e) {
            return ResultOBJ.ENROLL_ERROR;
        }
    }

    // 提交更新信息
    @PostMapping(value ="/postupdateinfo")
    public ResultOBJ postUpdateInfo(@RequestBody UserInfo userInfo){
        try {
            userService.postUpdateInfo(userInfo);
            return ResultOBJ.ADD_SUCCESS;
        } catch (Exception e) {
            return ResultOBJ.ADD_ERROR;
        }
    }

    // 管理员获取更新信息
    @GetMapping(value ="/getupdateinfo")
    public List<UserInfo> getUpdateInfo() {
        return userService.getUpdateInfo();
    }

    // 审批更新信息
    @PostMapping(value ="/approval")
    public ResultOBJ approvalComment(@RequestBody Approval approval){
        try {
            userService.approvalUpdateInfo(approval);
            return ResultOBJ.APPROVE_COMMENT_SUCCESS;
        } catch (Exception e) {
            return ResultOBJ.APPROVE_COMMENT_ERROR;
        }
    }

    // 更新用户信息接口
    @PutMapping(value = "/{id}")
    public ResultOBJ updateUserList(@PathVariable Integer id,@RequestBody User user){
        try {
            user.setId(id);
            userService.updateUser(user);

            return ResultOBJ.UPDATE_SUCCESS;
        } catch (Exception e) {
            return ResultOBJ.UPDATE_ERROR;
        }
    }

    // 注销用户接口
    @DeleteMapping(value = "/{id}")
    public ResultOBJ deleteUser(@PathVariable Integer id){
        try {
            userService.deleteUser(id);
            return ResultOBJ.DELETE_SUCCESS;
        } catch (Exception e) {
            return ResultOBJ.DELETE_ERROR;
        }
    }

    // 增加正确题数
    @PostMapping(value = "/addcorrectnum")
    public ResultOBJ addCorrectNum(@RequestBody String user_name){
        try {
            userService.addCorrectNum(user_name);
            return ResultOBJ.ACN_SUCCESS;
        } catch (Exception e) {
            System.out.println(e);
            return ResultOBJ.ACN_ERROR;
        }
    }
    // 增加错误题数
    @PostMapping(value = "/addwrongnum")
    public ResultOBJ addWrongNum(@RequestBody String user_name){
        try {
            userService.addWrongNum(user_name);
            return ResultOBJ.AWN_SUCCESS;
        } catch (Exception e) {
            return ResultOBJ.AWN_ERROR;
        }
    }

}
